package project.servlets;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class FileUpload
 */
@WebServlet("/upload")
public class FileUpload extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private final String UPLOAD_DIRECTORY = "C:/uploads";

	@Override
	protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		// process only if its multipart content
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
				for (FileItem item : multiparts) {
					if (!item.isFormField()) {
						String name = new File(item.getName()).getName();
						item.write(new File(UPLOAD_DIRECTORY + File.separator+ name));
					}
				}
				
				//request.setAttribute("message", "Plik zostal wrzucony poprawnie :)");
				//response.setHeader("Refresh", "3; URL=worker/added.jsp");
				response.setHeader("Refresh", "0; URL=counters/licznik_zgloszenie_pop.jsp");
			} catch (Exception ex) {
				//request.setAttribute("message", "Wrzucenie pliku nie powiodlo sie z powodu nastepujacego bledu: "+ ex);
				//response.setHeader("Refresh", "3; URL=worker/added.jsp");
				response.setHeader("Refresh", "0;URL=counters/licznik_zgloszenie_fail.jsp");
			}
		} else {
			//request.setAttribute("message","Blad serwera");
			//response.setHeader("Refresh", "3; URL=worker/added.jsp");
			response.setHeader("Refresh", "0; URL=counters/licznik_zgloszenie_serv.jsp");
		}
		request.getRequestDispatcher("/result.jsp").forward(request, response);
	}
}